﻿using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using QQ.Client;
using QQ.Packet;
using System.Collections.Generic;
using static QQ.Codecs.DotNettyByteBufferExtensions.LengthType;

namespace QQ.Codecs
{
    public class SSOFrameDecoder : MessageToMessageDecoder<HeadPacket>
    {
        public override bool IsSharable => true;

        private readonly LoginSigInfo loginSigInfo;
        private readonly ClientCallback clientCallback;

        public SSOFrameDecoder(ClientCallback clientCallback,LoginSigInfo loginSigInfo)
        {
            this.loginSigInfo = loginSigInfo;
            this.clientCallback = clientCallback;
        }

        protected override void Decode(IChannelHandlerContext context, HeadPacket msg, List<object> output)
        {
            Packet.Response.SSOFrame frame = new Packet.Response.SSOFrame()
            {
                packetSize = msg.body.ReadInt() - 4,
                SSOSequenceId = msg.body.ReadInt(),
                returnCode = msg.body.ReadInt(),
                extraData = msg.body.ReadBytesWithLength(INT, -4),
                commandName = msg.body.ReadBytesWithLength(INT, -4).GetString(),
                outgoingPacketSessionId = msg.body.ReadBytesWithLength(INT, -4),
                dataCompressed = msg.body.ReadInt()
            };
            if (frame.dataCompressed == 1)
            {
                msg.body.ReadInt();
                frame.plainBody = msg.body.ReadRemaingAndUnzip();
                System.Console.WriteLine($"解压缩成功");
            }
            else if (frame.dataCompressed == 0)
            {
                msg.body.ReadInt();
                frame.plainBody = msg.body.ReadRemaining();
            }
            else if (frame.dataCompressed == 8)
            {
                frame.plainBody = msg.body.ReadRemaining();
            }
            System.Console.WriteLine($"{nameof(Packet.Response.SSOFrame)}.{nameof(frame.commandName)}={frame.commandName}");
            loginSigInfo.outgoingPacketSessionId = frame.outgoingPacketSessionId;
            if (frame.commandName == "Heartbeat.Alive")
            {
                clientCallback.recvHeartBeat = true;
                System.Console.WriteLine($"检测到心跳包。{System.DateTime.Now}");
            }
            output.Add(frame);
        }
    }
}
